package com.YCH.behavior.service.impl;

import com.YCH.behavior.service.AppCommentBehaviorService;
import com.YCH.model.article.pojos.TbArticle;
import com.YCH.model.article.pojos.TbArticleComment;
import com.YCH.model.behavior.dtos.userCommentDto;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.TbArticleCommentMapper;
import com.YCH.model.mappers.app.TbArticleMapper;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.utils.common.ZipUtils;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings("all")
public class AppCommentBehaviorImpl implements AppCommentBehaviorService {
    @Autowired
    private TbArticleMapper tbArticleMapper;
    @Autowired
    private TbArticleCommentMapper tbArticleCommentMapper;
    @Override
    public ResponseResult comment(userCommentDto dto) {
        // 1.校验参数
        TbUser user = AppThreadLocalUtils.getUser();
        // 用户和用户id不能同时为空
        if (user == null && dto.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long userId = null;
        if (user != null) {
            userId = user.getId();
        }
        if(dto.getUserId()!=null){
            userId = dto.getUserId();
        }
        if(dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"文章id不能为空！");
        }
        if(dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"评论内容不能为空！");
        }
        // 2.判断该文章是否存在
        TbArticle tbArticle = tbArticleMapper.loadArticleById(dto.getArticleId());
        if(tbArticle == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章已被删除或者该文章已近下架！");
        }
        // 3.如果该文章存在，就插入评论
        Integer integer = 0;
        TbArticleComment tbArticleComment = new TbArticleComment();
        TbArticle tbArticle1 = new TbArticle();
        tbArticle1.setId(dto.getArticleId());
        tbArticleComment.setArticle(tbArticle1);
        tbArticleComment.setUserId(userId);
        tbArticleComment.setContent(ZipUtils.gzip(dto.getContent()));
        tbArticleComment.setCreatTime(new Date());
        if (dto.getCountyId() != null){
            tbArticleComment.setProvinceId(dto.getProvinceId());
            tbArticleComment.setCityId(dto.getCityId());
            tbArticleComment.setCountyId(dto.getCountyId());
            integer = tbArticleCommentMapper.insertHasLocation(tbArticleComment);
        }else {
            integer = tbArticleCommentMapper.insertNOLocation(tbArticleComment);
        }
        return ResponseResult.okResult(integer);
    }
}
